<?php

namespace Biz\service\search;

use Biz\cache\Coupon as cCoupon;
use Biz\cache\LimitationShop;
use Biz\model\activity\CouponConfig;
use Biz\model\GoodsBasicInfo;
use Biz\model\GoodsHeatDegree;
use Biz\model\PhotoRelaGoods;
use Biz\model\ShopCarouselBanner;
use Biz\module\Packages\Recommend\RecommendGoods;
use Biz\service\activity\FullShipping;
use Biz\service\BrandUser;
use Biz\service\CarouselBanner as sCarouselBanner;
use Biz\service\Category;
use Biz\service\Goods as sGoods;
use Biz\service\GoodsDetail;
use Biz\service\GoodsHistory;
use Biz\service\ShopClassify;
use Biz\service\Sku;
use Doraemon\service\MultiContent\MultiContent;
use Doraemon\service\Search;
use Doraemon\tools\Curl;
use Doraemon\tools\HhzClient;
use Doraemon\tools\Log as tLog;

/**
 * @deprecated
 */
class Goods extends BaseSearch
{
    const SOLR_SECTION = 'goods';

    const LIST_FUNC = 'buildListSearch';

    const RECOMMEND_LIST_FUNC = 'buildRecommendListSearchSql';


    const ACTIVITY_TYPE_FULLSHIPPING = 'fs_';

    const ACTIVITY_TYPE_CHANGE_PRICE_ACTIVITY = 'cpa';

    const ACTIVITY_TYPE_COUPON = 'cp_';

    const GOODS_TAG_SHIELD = "屏蔽商品";

    const SORT_TYPE_DEFAULE = 0;
    const SORT_TYPE_NEW = 1;
    const SORT_TYPE_PRICE_LOW = 2;
    const SORT_TYPE_PRICE_HIFH = 3;


    const HEAT_TAG_NEW = "新品";
    const HEAT_TAG_EXPLOSION = "爆款";
    const HEAT_TAG_HOT = "畅销";
    const HEAT_TAG_HIGH_EXPOSURE_UNSALABLE = "高曝光滞销";
    const HEAT_TAG_LOW_EXPOSURE_UNSALABLE = "低曝光滞销";
    const HEAT_TAG_HIGH_PV_UNSALABLE = "高PV滞销";

    const CATEGORY_SORT_DEFAULT_EXPLOSION_NUM = 10;
    const CATEGORY_SORT_DEFAULT_HOT_NUM = 8;
    const CATEGORY_SORT_DEFAULT_LOW_EXPOSURE_UNSALABLE_NUM = 2;


    /**
     * 更新goods solr 库 方法
     * @param $goods_id
     * @return array
     */
    public static function updateByGoodsId($goods_id)
    {
        $goodsDetail = GoodsDetail::formatBasicInfos([$goods_id])[$goods_id];
        $skuBasicInfos = Sku::SkuInfos([$goods_id], Sku::FIELDS_GROUP_BASE_WITH_STOCK)[$goods_id];
        if ($goodsDetail['spec_params']) {
            array_pop($goodsDetail['spec_params']);
            $material = $goodsDetail['spec_params'];
        } else {
            $material = [];
        }
        $path = self::getBasicUrl() . $goods_id;
        $data = [
            'id' => $goodsDetail['id'],
            'title' => $goodsDetail['title'],
            'brand_id' => $goodsDetail['brand_id'],
            'wiki_id' => $goodsDetail['wiki_id'],
            'shop_id' => $goodsDetail['shop_id'],
            'stock' => $goodsDetail['stock'],
            'sell_total' => $goodsDetail['sell_total'],
            'min_price' => $goodsDetail['min_price'],
            'max_price' => $goodsDetail['max_price'],
            'heat_degree' => GoodsHeatDegree::getCurrentDegree($goods_id),
            'activities' => self::activitiyTypeList($goods_id),
            'min_price_has_stock' => $skuBasicInfos['min_price'],
            'max_price_has_stock' => $skuBasicInfos['max_price'],
            'cate_id' => isset($goodsDetail['category'][0]) ? $goodsDetail['category'][0]['cate_id'] : '',
            'second_cate_id' => isset($goodsDetail['category'][1]) ? $goodsDetail['category'][1]['cate_id'] : '',
            'third_cate_id' => isset($goodsDetail['category'][2]) ? $goodsDetail['category'][2]['cate_id'] : '',
            'four_cate_id' => isset($goodsDetail['category'][3]) ? $goodsDetail['category'][3]['cate_id'] : '',
            'is_alarm' => (int)GoodsBasicInfo::admIsAlarm($goods_id),
            'cate' => isset($goodsDetail['category'][0]) ? $goodsDetail['category'][0]['cate_name'] : '',
            'second_cate' => isset($goodsDetail['category'][1]) ? $goodsDetail['category'][1]['cate_name'] : '',
            'third_cate' => isset($goodsDetail['category'][2]) ? $goodsDetail['category'][2]['cate_name'] : '',
            'four_cate' => isset($goodsDetail['category'][3]) ? $goodsDetail['category'][3]['cate_name'] : '',
            'material' => implode(' ', array_column($material, 'content')),
            'style' => str_replace(",", " ", $goodsDetail['style_content_desc']),
            'heat_tag' => '',
            'counter_rela_photos' => (int)PhotoRelaGoods::getRelaCounter($goods_id),
            'status' => $goodsDetail['status'],
            'addtime' => $goodsDetail['addtime'],
            'add_cart_num' => sGoods::admGetAddCartNums($goodsDetail['id']),
            'had_online' => $goodsDetail['had_online'],
            'first_online_time' => $goodsDetail['first_online_time'],
            'operate_time' => $goodsDetail['operate_time'],
            'operate_adminuid' => $goodsDetail['operate_adminuid'],
            'tags_content' => str_replace(",", " ", $goodsDetail['tags_content']),
            'app_status' => $goodsDetail['app_status'],
        ];
        $res = Curl::Request('POST', $path, ['form_params' => $data]);
        return $res;
    }


    // 双十一附加字段 现在已经不需要了
    public static function isInDouble11()
    {
        $startTime = strtotime('2018-11-01');
        $endTime = strtotime('2018-11-16');
        if ($startTime < time() && $endTime > time()) {
            return true;
        }
        return false;
    }

    // 满包邮信息 使用字段  activities 存储
    private static function activitiyTypeList($goodsId)
    {
        $fullShippingIds = FullShipping::getShippingByGoodsIdForSolor($goodsId);
        $fullShippingIds = isset($fullShippingIds[$goodsId]) ? array_map(function ($fullShippingId) {
            return self::ACTIVITY_TYPE_FULLSHIPPING . $fullShippingId;
        }, $fullShippingIds[$goodsId]) : [];

        $allActiviesType = array_merge($fullShippingIds, []);

        return implode(' ', $allActiviesType);
    }

    // 根据满包邮活动id 获取满包邮的商品列表
    // todo 待删除
    public static function searchGoodsByActivityId($activiyId, $page, $sortType, $pagesize = self::DEFAULT_PAGESIZE, $activityType = self::ACTIVITY_TYPE_FULLSHIPPING)
    {
        $condition = ['activities' => $activityType . $activiyId];
        $condition['sort'] = self::sortMapOnSearch($sortType);
        $res = self::searchByFields($condition, ['id'], $page, $pagesize);
        $res['rows'] = array_filter(array_column($res['rows'], 'id'), function ($id) {
            return is_integer($id);
        });

        return $res;
    }

    public static function getList($where, $field, $page, $pageSize)
    {
        return self::searchByFields($where, $field, $page, $pageSize);
    }

    /**
     * 关键词搜索商品基本入口
     * @param $keywords " 宜家 北欧 家电 液晶电视 "
     * @param int $shop_id
     */
    // 根据关键词或者tag搜索商品
    // 被商城首页搜索和商家首页搜索公用
    // todo 待删除
    public static function searchGoods($keywords, $addCondition = [], $buildSearchFun, $page = 1, $pagesize = self::DEFAULT_PAGESIZE)
    {
        $keywords = explode(" ", $keywords);
        $keywords = array_filter($keywords);
        if ($keywords) {
            $condition = self::$buildSearchFun($keywords);
            $addCondition = isset($addCondition) ? array_merge($condition, $addCondition) : $condition;
            tLog::debug('goods-search', [
                'uid' => HhzClient::getUid(),
                'condition' => $addCondition
            ]);
            $res = self::searchByFields($addCondition, [
                'id',
                'score'
            ], $page, $pagesize);
            $res['weight'] = array_column($res['rows'], 'score', 'id');
            $res['rows'] = array_filter(array_column($res['rows'], 'id'), function ($id) {
                return is_integer($id);
            });
            return $res;
        } else {
            throw new \Exception('关键词为空', __LINE__);
        }
    }

    // 通过上层传递的条件进行查询
    public static function searchByConditions(array $conditions, $sortType = 0, $page = 1, $pagesize = self::DEFAULT_PAGESIZE)
    {
        if (!isset($conditions['sort'])) {
            $conditions['sort'] = self::sortMap($sortType);
        }
        $res = self::searchByFields($conditions, ['id'], $page, $pagesize);
        $res['rows'] = array_filter(array_column($res['rows'], 'id'), function ($id) {
            return is_integer($id);
        });

        return $res;
    }

    // todo 目前没有项目在调用
    // todo 待删除
    public static function searchGoodsOnPubPhoto($keyword, $page, $pagesize = self::DEFAULT_PAGESIZE)
    {
        $addCondition = [
            'had_online' => GoodsBasicInfo::HAD_ONLINE_YES,
            'sort' => [
                'sell_total' => 'DESC',
                'first_online_time' => 'DESC'
            ]
        ];
        $Rst = [
            'list' => [],
            'is_over' => 1,
        ];

        $results = self::searchGoods($keyword, $addCondition, self::LIST_FUNC, $page, $pagesize);
        if ($results['total']) {
            $Rst['list'] = sGoods::Goods($results['rows'], sGoods::FIELDS_GROUP_COMMUNITY);
            $Rst['is_over'] = $results['is_over'];
            $Rst['count'] = $results['total'];
        } else {
            tLog::debug('search_goods_pub_photo', ['keyword' => $keyword]);
        }
        return $Rst;
    }

    // 排序规则
    private static function sortMap($sort_type)
    {
        $sort_map = [
            [
                'heat_degree' => 'DESC',
                'first_online_time' => 'DESC'
            ],
            ['first_online_time' => 'DESC'],
            ['min_price_has_stock' => 'ASC'],
            ['min_price_has_stock' => 'DESC'],
            ['id' => 'DESC'],
        ];

        return $sort_map[$sort_type];
    }

    // 如果等于0 的话默认按照销量排序
    private static function sortMapOnSearch($sortType)
    {
        return $sortType == 0 ? array_merge(['sell_total' => 'DESC'], self::sortMap($sortType)) : self::sortMap($sortType);
    }

    public static function searchTheparagraphGoodsByDs($keyWords, $sort, $areaCode, $uid, $page, $pageSize = self::DEFAULT_PAGESIZE)
    {
        $startNum = ($page - 1) * $pageSize;
        $result = [
            'list' => [],
            'recommed_list' => [],
            'is_over' => 0,
        ];
        $goodsIds = GoodsHistory::browseHistoryWithoutBought($uid, GoodsHistory::APP_SOURCE_THEPARAGRAPG);
        $recommendGoods = sGoods::Goods($goodsIds, sGoods::FIELDS_GROUP_LIST, $areaCode);
        $result['recommed_list'] = array_values($recommendGoods);
        $result['is_over'] = 1;
        return $result;
    }

    /**
     * 节选首页搜索
     * @param array $condition
     * @param $page int
     * @param $pageSize int
     * @param int $sortType
     * @return array
     */
    public static function searchTheparagraphGoodsByCondition($condition, $page, $pageSize = self::DEFAULT_PAGESIZE, $sortType = 0)
    {
        $defaultQuery = '!tags_content:节选不展示';
        $searchQuery = [
            'query' => $defaultQuery
        ];
        if (isset($condition['query'])) {
            $searchQuery['query'] = implode(' AND ', [$condition['query'], $searchQuery['query']]);
        }
        if (isset($condition['second_cate_id'])) {
            $searchQuery['second_cate_id'] = $condition['second_cate_id'];
        }
        if (!isset($condition['sort'])) {
            $searchQuery['sort'] = self::sortMap($sortType);
        }
        if (isset($condition['shop_id'])) {
            $searchQuery['shop_id'] = $condition['shop_id'];
        }
        if (isset($condition['tags_content'])) {
            $searchQuery['tags_content'] = $condition['tags_content'];
        }

        $result = self::searchByFields($searchQuery, ['id', 'shop_id', 'tags_content'], $page, $pageSize);
        return $result;
    }


    /**
     * 商品tag页 搜索商品
     * @param $keywords
     * @param $sort
     * @param $areaCode
     * @param $page
     * @param int $pagesize
     * @return array
     * @throws \Exception
     *
     */
    // todo 待删除
    public static function searchGoodsOnTab($keywords, $sort, $areaCode, $uid, $version, $page, $pagesize = self::DEFAULT_PAGESIZE)
    {
        $addCondition = [
            'tags_content' => ['not' => self::GOODS_TAG_SHIELD],
            'shop_id' => ['not' => LimitationShop::getAllShopIds()],
            'sort' => self::sortMapOnSearch($sort)
        ];

        $Rst = [
            'list' => [],
            'recommed_list' => [],
            'is_over' => 1,
        ];
//        // todo 搜索切换es待删除
        $results = self::searchGoods($keywords, $addCondition, self::LIST_FUNC, $page, $pagesize);

        // 如果不分词能查到的话，就返回结果。 如果查不到的话，用分词的方式，查询结果， 如果分词了还查不到的话，就返回浏览过但是没有买过的商品

        if ($results['total']) {
            $goodsList = sGoods::Goods($results['rows'], sGoods::FIELDS_GROUP_LIST, ['area_code' => $areaCode]);
            $goodsList = array_values($goodsList);
            if (version_compare($version, "3.9.0", ">=")) {
                $Rst['list'] = self::formatSearchResults($uid, $goodsList, $keywords, $page, $pagesize);
            } else {
                $Rst['list'] = $goodsList;
            }
        } else {
            tLog::debug('search_goods_list', [
                'uid' => HhzClient::getUid(),
                'keywords' => $keywords
            ]);
            $results = self::searchGoods($keywords, $addCondition, self::RECOMMEND_LIST_FUNC, $page, $pagesize);
            $results['total'] ? null : tLog::debug('search_goods_recommend_list', [
                'uid' => HhzClient::getUid(),
                'keywords' => $keywords
            ]);
            $recommendList = sGoods::Goods($results['rows'], sGoods::FIELDS_GROUP_LIST, ['area_code' => $areaCode]);
            if (version_compare($version, "3.9.0", ">=")) {
                foreach ($recommendList as $item) {
                    $Rst['recommed_list'][] = [
                        'type' => RecommendGoods::GOODS_TYPE,
                        'goods_info' => $item
                    ];

                }
            } else {
                $Rst['recommed_list'] = array_values($Rst['recommed_list']);
            }
        }

        $Rst['is_over'] = $results['is_over'];

        return $Rst;
    }

    // 处理搜索结果 在搜索结果中嵌套banner
    //todo 待删除
    private static function formatSearchResults($uid, $goodsList, $keywords, $page, $pagesize)
    {
        $resutls = [];
        $carouseBanners = sCarouselBanner::getMultipleBanner($uid, date("Y-m-d H:i:s"));
        $carouseBanners = array_column($carouseBanners, null, 'type');
        $carouseBanner = $carouseBanners[1028];
        $carouseBanner = self::filterCarouseBanner($keywords, $carouseBanner, $page, $pagesize);
        foreach ($goodsList as $k => $item) {
            $resutls[] = [
                'type' => RecommendGoods::GOODS_TYPE,
                'goods_info' => $item,
                'stat_info' => MultiContent::getSearchStat($page, $pagesize * $page + ($k + 1), $uid, MultiContent::CONTENT_FROM_SEARCH)
            ];
            if ($carouseBanner['search_results'] && ($k + 1) % 2 == 0) {
                $banner = array_shift($carouseBanner['search_results']);
                $resutls[] = [
                    'type' => ShopCarouselBanner::TYPE_APP_BANNER_INFO,
                    'banner_info' => $banner
                ];
            }
        }
        return $resutls;
    }

    // 过滤banner
    //todo 待删除
    private static function filterCarouseBanner($keywords, $carouseBanner, $page, $pagesize)
    {
        // 将 关键字 转换为数组
        $keywords = explode(' ', $keywords);
        $searchResult = [];
        if (isset($carouseBanner['search_results']) && $carouseBanner['search_results']) {
            foreach ($carouseBanner['search_results'] as $item) {
                // 将tag转换为数组
                // 如果 关键字和tag有交集的话，返回banner
                if (array_intersect(explode(',', $item['banner_desc']), $keywords)) {
                    $searchResult[] = $item;
                }
            }
        }

        if (isset($searchResult[($page - 1) * $pagesize / 4])) {
            $searchResult = array_slice($searchResult, ($page - 1) * $pagesize / 4, $pagesize / 4); //防止每页的banner重复  所以 截取
        } else {
            $searchResult = [];
        }
        $carouseBanner['search_results'] = $searchResult;
        return $carouseBanner;
    }


    /**
     * 店铺内搜索商品
     * @param $keywords
     * @param $shop_id
     * @param $sort
     * @param $province_id
     * @param $page
     * @param int $pagesize
     * @return array
     * @throws \Exception
     *
     */
    // todo 待删除
    public static function searchGoodsOnShop($keywords, $shopId, $sort, $areaCode, $page, $pagesize = self::DEFAULT_PAGESIZE)
    {
        $BrandUserType = BrandUser::getBrandUserType($shopId);
        $Rst = [
            'list' => [],
            'is_over' => 1,
        ];
        if ($BrandUserType == BrandUser::BRAND_USER_TYPE_A) {
            throw new \Exception('A类品牌没有商品');
        } else if ($BrandUserType == BrandUser::BRAND_USER_TYPE_B || $BrandUserType == BrandUser::BRAND_USER_TYPE_C) {
            $addCondition = [
                'shop_id' => $shopId,
            ];
        } else if ($BrandUserType == BrandUser::BRAND_USER_TYPE_D) {
            $addCondition = [
                'brand_id' => BrandUser::getUserBrandId($shopId),
            ];
        } else {
            return $Rst;
        }
        $addCondition = array_merge($addCondition, [
            'sort' => self::sortMapOnSearch($sort)
        ]);
        $results = self::searchGoods($keywords, $addCondition, self::LIST_FUNC, $page, $pagesize);
        if ($results['total']) {
//			$Rst['list'] = GoodsDetail::FormatBasicInfoOnGoodsInfoList($results['rows'], [], $province_id, 0,['brand_info', 'category_name']);
            $Rst['list'] = sGoods::Goods($results['rows'], sGoods::FIELDS_GROUP_LIST, $areaCode);;
            $Rst['list'] = array_values($Rst['list']);
            $Rst['is_over'] = $results['is_over'];
        }
        return $Rst;

    }

    /**
     * 根据商品TAG取商品
     * @param $tagName
     * @param $sortType
     * @param int $page
     * @param int $pagesize
     * @param array $params
     * @return array
     */
    //todo 待删除
    public static function searchGoodsByTag($tagName, $sortType, $page = 1, $pagesize = self::DEFAULT_PAGESIZE, $params = [])
    {

        $params = ShopClassify::verifyParams($params);
        $results = self::searchByFields(array_merge([
            'price_range' => isset($params['price_range']) ? $params['price_range'] : [],
            'brand_id' => isset($params['brand']) ? $params['brand'] : [],
        ], [
            'tags_content' => $tagName,
            'query' => " !tags_content:(" . self::GOODS_TAG_SHIELD . ") ",
            'sort' => self::sortMap($sortType),
        ]), ['id'], $page, $pagesize);
        $results['rows'] = array_filter(array_column($results['rows'], 'id'), function ($id) {
            return is_integer($id);
        });
        return $results;
    }

    // todo 待删除
    private static function buildRecommendListSearch($keywords, $isAnalysis = false)
    {
        $condition = [];
        $BrandRst = Brand::searchByFields(['brand_alias' => $keywords]);
        $brandIds = array_column($BrandRst['rows'], 'id');
        if ($brandIds) {
            $condition['OR']['brand_id'] = $brandIds;
        }
        $condition['OR']['title'] = $keywords;
        $condition['OR']['material'] = $keywords;
        $condition['OR']['style'] = $keywords;
        $condition['OR']['category_name'] = $keywords;
        if ($isAnalysis) {
            $worlds = [];
            foreach ($keywords as $keyword) {
                $worlds = array_merge($worlds, Search::_getScwsTag($keyword));
            }
            if ($worlds) $condition['OR']['category_name'] = array_merge($condition['OR']['category_name'], $worlds);

            // 如果没有结果  返回  用户浏览过 却 没有买过的商品id
            if (!self::isHasAnalysisResult($condition)) {
                return ['id' => GoodsHistory::browseHistoryWithoutBought(HhzClient::getUid())];
            }
        }

        return $condition;
    }

    // todo 待删除
    private static function isHasAnalysisResult($condition)
    {
        $result = self::searchByFields($condition);
        return (boolean)$result['total'];
    }


    // todo 待删除
    private static function buildRecommendListSearchSql($keywords)
    {
        $condition = self::buildRecommendListSearch($keywords, true);
        return $condition;
    }

    // todo 待删除
    private static function buildListSearch($keywords)
    {
        $condition = [];
        foreach ($keywords as $keyword) {
            $OrConditions[] = self::buildRecommendListSearch([$keyword]);
        }

        foreach ($OrConditions as $k => $orCondition) {
            $condition['AND']['OR_' . "#" . $k] = $orCondition['OR'];
        }
        return $condition;
    }


    /**
     *商城类目二级页
     */
    // todo 待删除
    public static function searchGoodsByCateIds($cateIds, $sortType, $page, $pagesize = self::DEFAULT_PAGESIZE, $addConditions = [])
    {
        $result = [
            'rows' => [],
            'total' => 0,
            'is_over' => 1,
        ];

        if ($cateIds) {
            $searchQuery = $addConditions ?: [
                'tags_content' => ['not' => self::GOODS_TAG_SHIELD],
                'shop_id' => ['not' => LimitationShop::getAllShopIds()],
            ];
            if ($addConditions) $searchQuery = array_merge($searchQuery, $addConditions);
            $searchQuery['category_id'] = $cateIds;
            $searchQuery['sort'] = self::sortMap($sortType);
            if (Goods::isInDouble11() && $sortType == 0) {
                $searchQuery['activities'] = [Goods::ACTIVITY_TYPE_CHANGE_PRICE_ACTIVITY];
            }
            $result = self::searchByFields($searchQuery, ['id'], $page, $pagesize);
            if (Goods::isInDouble11() && $sortType == 0 && $result['is_over']) {
                $preGoodsIds = $result['rows'];
                unset($searchQuery['activities']);
                $searchQuery['activities'] = ['not' => [Goods::ACTIVITY_TYPE_CHANGE_PRICE_ACTIVITY]];
                $page = $page - floor($result['total'] / $pagesize);
                $result = self::searchByFields($searchQuery, ['id'], $page, $pagesize);
                $result['rows'] = array_merge($preGoodsIds, $result['rows']);
            }
            $result['rows'] = array_filter(array_column($result['rows'], 'id'), function ($id) {
                return is_integer($id);
            });
        }
        return $result;
    }

    // todo 目前没有调用的方法
    public static function searchGoodsByCateIdsWithHeatTag($cateIds, $sortType, $page, $pagesize = self::DEFAULT_PAGESIZE, $addConditions = [])
    {
        $result = [
            'rows' => [],
            'total' => 0,
            'is_over' => 1,
        ];

        if ($cateIds) {
            $searchQuery = [
                'tags_content' => ['not' => self::GOODS_TAG_SHIELD],
                'shop_id' => ['not' => LimitationShop::getAllShopIds()],
            ];
            if ($addConditions) {
                $searchQuery = array_merge($searchQuery, $addConditions);
            }
            $searchQuery['category_id'] = $cateIds;
            switch ($sortType) {
                case self::SORT_TYPE_DEFAULE:
                    //取爆款
                    $queryParams = array_merge($searchQuery, [
                        'heat_tag' => self::HEAT_TAG_EXPLOSION,
                        'sort' => ['exposure' => 'DESC']
                    ]);
                    $explosionGoods = self::searchByFields($queryParams, ['id'], $page, self::CATEGORY_SORT_DEFAULT_EXPLOSION_NUM);
                    //取畅销
                    $queryParams = array_merge($searchQuery, [
                        'heat_tag' => self::HEAT_TAG_HOT,
                        'sort' => ['exposure' => 'DESC']
                    ]);
                    $hotGoods = self::searchByFields($queryParams, ['id'], $page, self::CATEGORY_SORT_DEFAULT_HOT_NUM);
                    //取低曝光滞销
                    $queryParams = array_merge($searchQuery, [
                        'heat_tag' => self::HEAT_TAG_LOW_EXPOSURE_UNSALABLE,
                        'sort' => ['exposure' => 'DESC']
                    ]);
                    $lowExposureUnsalableGoods = self::searchByFields($queryParams, ['id'], $page, self::CATEGORY_SORT_DEFAULT_LOW_EXPOSURE_UNSALABLE_NUM);
                    //取其他商品
                    $queryParams = array_merge($searchQuery, [
                        'heat_tag' => [
                            'not' => [
                                self::HEAT_TAG_EXPLOSION,
                                self::HEAT_TAG_HOT,
                                self::HEAT_TAG_LOW_EXPOSURE_UNSALABLE
                            ]
                        ],
                        'sort' => ['exposure' => 'DESC']
                    ]);
                    $otherGoods = self::searchByFields($queryParams, ['id'], $page, self::CATEGORY_SORT_DEFAULT_EXPLOSION_NUM);
                    break;
                case self::SORT_TYPE_NEW:
                case self::SORT_TYPE_PRICE_LOW:
                case self::SORT_TYPE_PRICE_HIFH:
                    $searchQuery['sort'] = self::sortMap($sortType);
                    $result = self::searchByFields($searchQuery, ['id'], $page, $pagesize);
                    $result['rows'] = array_filter(array_column($result['rows'], 'id'), function ($id) {
                        return is_integer($id);
                    });
                    break;
            }
        }
        return $result;
    }

    private static function getPageSize($page, $pageSize, $typePageSize, $solrResult)
    {
        if ($solrResult['rows']) {
            return [
                'start' => ($page - 1) * ($pageSize - $typePageSize),
                'pageSize' => $pageSize - count($solrResult['rows']),
            ];
        } else {
            return [
                'start' => $page * $pageSize - $solrResult['total'],
                'pageSize' => $pageSize,
            ];
        }
    }


    /**
     * 根据品牌 与 类目 交集 取maxcounter个商品IDS
     * @param $brandIds
     * @param $cateIds
     * @param $maxCounter
     * @param $notGIds
     */
    // todo 待删除
    public static function searchGoodsIdsByBrandIdsAndCateIds($brandIds, $cateIds, $maxCounter, $notGIds)
    {
        $rstGoodsIds = [];
        $brandIds = array_unique($brandIds);
        $cateIds = array_unique($cateIds);
        foreach ($brandIds as $brandId) {
            foreach ($cateIds as $cateId) {
                if (count($rstGoodsIds) < $maxCounter) {
                    $condition['brand_id'] = $brandId;
                    $condition['last_category_id'] = $cateId;
                    $condition['tags_content'] = ['not' => self::GOODS_TAG_SHIELD];
                    $condition['shop_id'] = ['not' => LimitationShop::getAllShopIds()];
                    if ($notGIds) {
                        $condition['id'] = ['not' => $notGIds];
                    }
                    $condition['sort'] = self::randomSort();
                    $result = self::searchByFields($condition, ['id'], 1, 3); //每个
                    $goodsIds = array_filter(array_column($result['rows'], 'id'), function ($id) {
                        return is_integer($id);
                    });

                    $notGIds = array_merge($notGIds, $goodsIds);
                    $rstGoodsIds = array_merge($rstGoodsIds, $goodsIds);
                } else {
                    break;
                }
            }
        }
        return $rstGoodsIds;
    }

    // todo 待删除
    public static function searchGoodsIdsByLastCateIds($cateIds, $maxCounter, $notGids)
    {
        $rstGoodsids = [];
        $cateIds = array_unique($cateIds);
        foreach ($cateIds as $cateId) {
            if (count($rstGoodsids) < $maxCounter) {
                $condition['last_category_id'] = $cateId;
                $condition['tags_content'] = ['not' => self::GOODS_TAG_SHIELD];
                $condition['shop_id'] = ['not' => LimitationShop::getAllShopIds()];
                $condition['id'] = ['not' => $notGids];
                $condition['sort'] = self::randomSort();

                $result = self::searchByFields($condition, ['id'], 1, 3); //每个
                $goodsIds = array_filter(array_column($result['rows'], 'id'), function ($id) {
                    return is_integer($id);
                });

                $notGids = array_merge($notGids, $goodsIds);
                $rstGoodsids = array_merge($rstGoodsids, $goodsIds);
            } else {
                break;
            }
        }
        return $rstGoodsids;
    }

    // todo 待删除
    public static function searchGoodsIdsByCateNamesAndBrandIds($cateNames, $BrandIds, $maxCounter, $notGids)
    {
        $goodsIds = [];
        if ($cateNames) {
            if ($BrandIds) {
                $condition['brand_id'] = $BrandIds;
                $goodsIds = self::searchGoodsIdsByCateNames($cateNames, $maxCounter, $notGids, ['brand_id' => $BrandIds]);
            }
            if (count($goodsIds) < $maxCounter) {
                $maxCounter = $maxCounter - count($goodsIds);
                $goodsIds = array_merge($goodsIds,
                    self::searchGoodsIdsByCateNames($cateNames, $maxCounter, $goodsIds)
                );
            }
            if (count($goodsIds) < $maxCounter) {
                $maxCounter = $maxCounter - count($goodsIds);
                $goodsIds = array_merge($goodsIds,
                    self::searchGoodsIdsBySameLevelCateNames($cateNames, $maxCounter, $goodsIds)
                );
            }
        }
        return $goodsIds;
    }

    // todo 待删除
    private static function searchGoodsIdsBySameLevelCateNames($cateNames, $maxCounter, $notGids, $searchField = 'third_cate')
    {
        $findFieldMap = [
            'third_cate' => 'second_cate_id',
            'four_cate' => 'third_cate_id',
        ];
        $results = self::searchByFields(array_merge([$searchField => $cateNames],
            [
                'tags_content' => ['not' => self::GOODS_TAG_SHIELD],
                'shop_id' => ['not' => LimitationShop::getAllShopIds()]
            ]), [$findFieldMap[$searchField]], 1, count($cateNames));
        $parentCateIds = array_column($results['rows'], $findFieldMap[$searchField]);
        $goodsIds = [];
        $parentCateIds = array_unique($parentCateIds);
        foreach ($parentCateIds as $parentCateId) {
            if (count($goodsIds) < $maxCounter) {
                $condition[$findFieldMap[$searchField]] = $parentCateId;
                $condition['tags_content'] = ['not' => self::GOODS_TAG_SHIELD];
                $condition['shop_id'] = ['not' => LimitationShop::getAllShopIds()];
                $condition['id'] = ['not' => $notGids];
                $condition['sort'] = self::randomSort();
                $results = self::searchByFields($condition, ['id'], 1, 3);
                $goodsIds = array_merge($goodsIds, array_column($results['rows'], 'id'));
                $notGids = array_merge($notGids, array_column($results['rows'], 'id'));
            }
        }
        if (count($goodsIds) < $maxCounter && $searchField != 'four_cate') {
            $goodsIds = array_merge($goodsIds,
                self::searchGoodsIdsBySameLevelCateNames($cateNames, $maxCounter - count($goodsIds), $notGids, 'four_cate')
            );
        }
        return $goodsIds;
    }

    // todo 待删除
    private static function searchGoodsIdsByCateNames($cateNames, $maxCounter, $notGids, $addCondition = [])
    {
        $goodsIds = [];
        $condition = $addCondition;
        foreach ($cateNames as $cateName) {
            if (count($goodsIds) < $maxCounter) {
                $condition['last_category_name'] = $cateName;
                $condition['tags_content'] = ['not' => self::GOODS_TAG_SHIELD];
                $condition['shop_id'] = ['not' => LimitationShop::getAllShopIds()];
                $condition['id'] = ['not' => $notGids];
                $condition['sort'] = self::randomSort();
                $result = self::searchByFields($condition, ['id'], 1, 3);
                $goodsIds = array_merge($goodsIds, array_filter(array_column($result['rows'], 'id'), function ($id) {
                    return is_integer($id);
                }));
                $notGids = array_merge($notGids, $goodsIds);
            } else {
                break;
            }
        }
        return $goodsIds;
    }

    // todo 待删除
    public static function recommendGoods($goodsId, $shopId, $categoryIds, $maxCount = 20)
    {
        $searchQuery['category_id'] = $categoryIds;
        $searchQuery['tags_content'] = ['not' => self::GOODS_TAG_SHIELD];
        $searchQuery['shop_id'] = $shopId;
        $searchQuery['id']['not'] = $goodsId;
        $searchQuery['sort'] = [
            'four_cate_id' => 'DESC',
            'third_cate_id' => 'DESC',
            'second_cate_id' => 'DESC',
            'cate_id' => 'DESC'
        ];
        $result = self::searchByFields($searchQuery, ['id'], 1, $maxCount);
        $goodsIds = array_filter(array_column($result['rows'], 'id'), function ($id) {
            return is_integer($id);
        });
        if (count($goodsIds) < $maxCount) {
            $searchQuery = [];
            $searchQuery['shop_id'] = $shopId;
            $searchQuery['id']['not'] = array_merge($goodsIds, [$goodsId]);
            $result = self::searchByFields($searchQuery, ['id'], 1, $maxCount - count($goodsIds));
            $otherGoodsIds = array_filter(array_column($result['rows'], 'id'), function ($id) {
                return is_integer($id);
            });
            shuffle($otherGoodsIds);
            $goodsIds = array_merge($goodsIds, $otherGoodsIds);
        }

        return $goodsIds;
    }

    public static function randomSort()
    {
        $fields = [
            'id',
            'stock',
            'sell_total',
            'min_price',
            'max_price',
            'min_price_has_stock',
            'max_price_has_stock',
            'addtime',
            'operate_time',
            'first_online_time',
            'heat_degree'
        ];

        return [$fields[array_rand($fields)] => 'DESC'];
    }

    // 过滤屏蔽商品
    // todo 待删除
    public static function filterShieldGoodsIds($goodsIds, $addCondition = [])
    {
        $condition = [
            'id' => $goodsIds,
            'tags_content' => ['not' => self::GOODS_TAG_SHIELD],
            'shop_id' => ['not' => LimitationShop::getAllShopIds()]
        ];
        if ($addCondition) {
            $condition = array_merge($condition, $addCondition);
        }
        $results = self::searchByConditions($condition, 0, 1, count($goodsIds));
        $filterShieldGoodsIds = [];
        foreach ($goodsIds as $goodsId) {
            if (in_array($goodsId, $results['rows'])) {
                $filterShieldGoodsIds[] = $goodsId;
            }
        }
        return $filterShieldGoodsIds;
    }

    /**
     * @desc 搜索一级类目商品
     * @param array $categoryIds
     * @param array $goodsIds
     * @param array $addCondition
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    // todo 待删除
    public static function searchGoodsByTopCateIds(array $categoryIds, array $goodsIds, array $addCondition = [], $page = 1, $pageSize = self::DEFAULT_PAGESIZE)
    {
        $condition = [
            'category_id' => $categoryIds,
            'id' => ['not' => $goodsIds],
            'tags_content' => ['not' => self::GOODS_TAG_SHIELD],
            'shop_id' => ['not' => LimitationShop::getAllShopIds()]
        ];
        if ($addCondition) {
            $condition = array_merge($condition, $addCondition);
        }
        $results = self::searchByConditions($condition, 0, $page, $pageSize);
        $results = isset($results['rows']) ? $results['rows'] : [];
        return $results;
    }

    // todo 待删除
    public static function searchGoodsByClassifies($classifyIds, $minPrice, $maxPrice, $couponIf, $sortType, $page)
    {
        $search = [];
        $cateIds = [];
        foreach ($classifyIds as $classifyId) {
            $classifyInfo = Category::getCateIdsByClassifyId($classifyId);
            $cateIds = array_merge($cateIds, $classifyInfo['cate_ids']);
        }
        $search['category_id'] = $cateIds;
        $couponConfig = cCoupon::getConfig($couponIf); // 查看优惠券是否存在 $couponIf = 优惠券id
        if (!$couponConfig) {
            throw new \Exception('优惠券不存在');
        }
        if ($couponConfig['assume'] && $couponConfig['assume'] == CouponConfig::COUPON_ASSUME_SHOP) { // assume = 承担方
            $search['shop_id'] = $couponConfig['shop_id'];
        }
        if ($couponConfig['cate_scope'] == CouponConfig::CATE_SCOPE_NOT_ALL) {
            $tmpCates = array_filter(explode('|', $couponConfig['cate_ids']));
            foreach ($tmpCates as $cate) {
                $search['category_id'] = array_merge($search['category_id'], array_filter(explode('-', $cate)));
            }
        }
        if ($couponConfig['include_goods_ids']) {
            $search['id'] = array_filter(explode(',', $couponConfig['include_goods_ids']));
        }
        if ($minPrice && $maxPrice) {
            $search['price_range'] = [
                $minPrice,
                $maxPrice
            ];
        } else if ($minPrice) {
            $search['min_price'] = $minPrice;
        } else if ($maxPrice) {
            $search['max_price'] = $maxPrice;
        }

        $results = self::searchByConditions($search, $sortType, $page);
        $results = isset($results['rows']) ? $results : [];
        return $results;
    }

}
